package com.example.controller;

import cn.hutool.core.io.FileUtil;
import com.example.common.Result;
import com.example.exception.CustomException;
import com.example.util.AliOssUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {

    /**
    多文件上传
     */
    @PostMapping("/uploadManyFiles")
    public Result uploadManyFiles(MultipartFile[] files) {
        if (files == null || files[0].isEmpty()) throw new CustomException("400","上传文件为空");
        List<String> urls =new ArrayList<>();
        for (MultipartFile file : files){
            String url = "";
            String originalFilename = file.getOriginalFilename();//获取文件名 xxx.png
            String filename = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
            try {
                url = AliOssUtil.uploadFile(filename, file.getInputStream());
                urls.add(url);
            }catch (Exception e){
                e.printStackTrace();
                throw new CustomException("500","文件上传失败");
            }
        }

        return Result.success(urls);
    }
/**
 * 单文件上传
 */
@PostMapping("/upload")
       public Result upload(MultipartFile file) {
       if (file == null || file.isEmpty()) throw new CustomException("400","上传文件为空");
            String url = "";
            String originalFilename = file.getOriginalFilename();//获取文件名 xxx.png
            String filename = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
            try {
                url = AliOssUtil.uploadFile(filename, file.getInputStream());

            }catch (Exception e){
                e.printStackTrace();
                throw new CustomException("500","文件上传失败");

            }
        return Result.success(url);
    }
}
